﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using volva.Models;

namespace volva.Services
{
    public class MessageService
    {
        /// <summary>
        /// This function is used when a user wants to send message.
        /// </summary>
        /// <param name="model">Information about message.</param>
        static public void Send(Message model)
        {
            Message message = new Message
            {
                body = model.body,
                isNew = model.isNew,
                subject = model.subject,
                WebUser_from_id = model.WebUser_from_id,
                WebUser_to_id = model.WebUser_to_id
            };
            DataService.ddc.Messages.InsertOnSubmit(message);
            DataService.ddc.SubmitChanges();
        }
        
        /// <summary>
        /// This function shows user's messages.
        /// </summary>
        /// <param name="userID">Which user's messages to show.</param>
        /// <returns>List of objects, that is the user's messages.</returns>
        static public List<Message> GetMessages(int userID)
        {
            List<Message> messages =
            (from m in DataService.ddc.Messages
            where m.WebUser_to_id == userID
            orderby m.id descending
            select m).ToList();

            return messages;
        }
        /// <summary>
        /// Deletes a message
        /// </summary>
        /// <param name="model">The message model</param>
        static public void Delete(Message model)
        {
            DataService.ddc.Messages.DeleteOnSubmit(model);
            DataService.ddc.SubmitChanges();
        }
        static public Message GetMessage(int messageId)
        {
            Message message =
                (from m in DataService.ddc.Messages
                where m.id == messageId
                select m).SingleOrDefault();

            return message;
        }
        static public int GetNewMessageCount(int userId)
        {
            int messageCount = (from m in DataService.ddc.Messages
                                where m.WebUser_to_id == userId
                                && m.isNew == true    // Missing from the database.
                                select m).Count();

            return messageCount;
        }

        static public void MarkMessageAsRead(int id)
        {
            Message message = MessageService.GetMessage(id);
            message.isNew = false;
            DataService.ddc.SubmitChanges();
        }
    }
}
